package arraylist;

public class MyArrayList {
    //表示一整组数据
    public String[] data = null;
    //表示实际存储数据多少
    public int size = 0;

    //默认构造方法,容量初始化为 10
    public MyArrayList(){
        data = new String[10];
    }
    // 指定容量
    public MyArrayList(int capacity){
        if (capacity <= 10){
            capacity = 10;
        }
        data = new String[capacity];
    }

    //扩容操作
    public void recapacity(){
        //1.创建新数组把容量扩大到原来的1.5倍
        String[] newData = new String[(int)(data.length * 1.5)];
        //2.旧数组的元素复制到新数组上
        for (int i = 0; i < data.length; i++){
            newData[i] = data[i];
        }
        //3.新数组代替旧数组
        data = newData;
    }
    //尾插
    public void add(String elem){
        //需要判断是否容量满了
        //满了就需要扩容
        if (size >= data.length){
            recapacity();
        }
        data[size] = elem;
        size++;
    }
    //往指定位置插入
    public void add(int index, String elem){
        //判断 index 是否合法
        if (index < 0 && index > size){
            //抛出异常
            throw new IndexOutOfBoundsException("Index" + index + ",size" + size);
        }
    }

    public String toString(){
        //StringBuilder 可以拼接字符串
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[");
        for (int i = 0; i < size; i++){
            stringBuilder.append(data[i]);
            if (i < size - 1){
                stringBuilder.append(", ");
            }
        }
        stringBuilder.append("]");
        return stringBuilder.toString();
    }
    public static void main(String[] args) {
        MyArrayList list = new MyArrayList();
        list.add("hello");
        list.add("world");
        System.out.println(list);
    }
}
